﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SiGeSIB.Data.Common;
using System.Xml;
using System.Collections;

namespace SiGeSIB.Data.Security
{
	public class ConnectionSchemaCollection : IEnumerable<ConnectionSchema>, IContentsSerializable
	{
		public ConnectionSchemaCollection(XmlNode node)
			: this()
		{
			Deserialize(node);
		}
		public ConnectionSchemaCollection()
		{
			_Connections = new Dictionary<int, ConnectionSchema>();
		}

		#region Attributes
		private Dictionary<int, ConnectionSchema> _Connections;
		private int _ConnectionIndex = 0;
		#endregion

		#region Properties
		public ConnectionSchema SelectedSchema { get; set; }
		public string XmlElementName { get { return "Connections"; } }
		#endregion

		#region IEnumerable<ConnectionSchema> Members

		public IEnumerator<ConnectionSchema> GetEnumerator()
		{
			return _Connections.Select<KeyValuePair<int, ConnectionSchema>, ConnectionSchema>(pair => pair.Value).GetEnumerator();
		}

		#endregion

		#region IEnumerable Members

		IEnumerator IEnumerable.GetEnumerator()
		{
			return _Connections.GetEnumerator();
		}

		#endregion

		#region IContentsSerializable Members

		public void Serialize(XmlWriter xmlw)
		{
			xmlw.WriteStartElement(XmlElementName);

			foreach (var pair in _Connections)
				pair.Value.Serialize(xmlw);

			xmlw.WriteEndElement();
		}

		public void Deserialize(XmlNode node)
		{
			if (node != null && node[XmlElementName] != null)
			{
				foreach (XmlElement no in node[XmlElementName].ChildNodes)
				{
					ConnectionSchema conn = new ConnectionSchema();
					conn.Deserialize(no);

					UpdateConnection(conn);
				}
			}
		}

		#endregion

		#region Methods
		public int UpdateConnection(ConnectionSchema conn)
		{
			// Se a nova conexão é padrão, reseta as outras padrão
			if (conn.IsDefaultConnection)
			{
				foreach (var pair in _Connections)
					if (pair.Value != conn)
						pair.Value.IsDefaultConnection = false;

				SelectedSchema = conn;
			}

			// Se é uma conexão existente
			if (conn.Id > 0 && _Connections.ContainsKey(conn.Id))
			{
				_Connections[conn.Id] = conn;
				if (conn.Id > _ConnectionIndex)
					_ConnectionIndex = conn.Id;
			}
			else
			{
				conn.Id = ++_ConnectionIndex;
				_Connections.Add(conn.Id, conn);
			}

			return conn.Id;
		}

		public ConnectionSchema this[int i] { get { return _Connections[i]; } }

		public ConnectionSchema GetSchema(int id)
		{
			return _Connections.ContainsKey(id) ? _Connections[id] : null;
		}
		#endregion

		public void Remove(int id)
		{
			if (_Connections.ContainsKey(id))
				_Connections.Remove(id);
		}
	}
}
